using System.Windows;
using System.Windows.Controls;

namespace TrackMe.View.Behaviours
{
	public static class ListBoxBehaviourScrollSelectedIntoView
	{
		public static bool GetActive(ListBox listBox)
		{
			return (bool)listBox.GetValue(ActiveProperty);
		}

		public static void SetActive(ListBox listBox, bool value)
		{
			listBox.SetValue(ActiveProperty, value);
		}

		public static readonly DependencyProperty ActiveProperty =
			DependencyProperty.RegisterAttached(
			"Active",
			typeof(bool),
			typeof(ListBoxBehaviourScrollSelectedIntoView),
			new UIPropertyMetadata(false, OnActiveChanged));

		static void OnActiveChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
		{
			var item = depObj as ListBox;
			if (item == null)
				return;

			if (e.NewValue is bool == false)
				return;

			if ((bool)e.NewValue)
				item.SelectionChanged += OnListBoxSelectionChanged;
			else
				item.SelectionChanged -= OnListBoxSelectionChanged;
		}

		static void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var newSel = e.AddedItems;
			var listBox = e.OriginalSource as ListBox;
			
			if (newSel.Count == 1 && listBox != null)
				listBox.ScrollIntoView(newSel[0]);
		}

		
	}
}